<template>
  <div class="app-container">
     
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  label-width="100px">
        <el-form-item label="申请人" prop="userId">
          <el-select
            v-model="queryParams.userId"
            placeholder="请选择申请人"
            clearable
            filterable
          >
            <el-option v-for="user in userList" :key="user.userId" :label="user.userName" :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请地点" prop="locationId">
          <el-select
            v-model="queryParams.locationId"
            placeholder="请选择申请地点"
            clearable
            filterable
          >
            <el-option v-for="location in locationList" :key="location.locationId" :label="location.locationName" :value="location.locationId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调取开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="queryParams.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择调取开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="调取结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="queryParams.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择调取结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
            <el-option label="待审批" value="0"></el-option>
            <el-option label="已批准" value="1"></el-option>
            <el-option label="已拒绝" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

   
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['monitor:request:add']"
          >新增申请</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-check"
            size="mini"
            :disabled="single"
            @click="handleApprove"
            v-if="isAdmin"
            v-hasPermi="['monitor:request:edit']"
          >批准</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-close"
            size="mini"
            :disabled="single"
            @click="handleReject"
            v-if="isAdmin"
            v-hasPermi="['monitor:request:edit']"
          >拒绝</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['monitor:request:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

   
      <el-table 
        v-loading="loading" 
        :data="requestList" 
        @selection-change="handleSelectionChange" 
        class="custom-table"
        stripe
        border
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="申请编号" align="center" prop="requestId" width="100" />
        <el-table-column label="申请人" align="center" prop="userName" width="120" />
        <el-table-column label="申请地点" align="center" prop="locationName" width="120" />
        <el-table-column label="调取开始时间" align="center" prop="startTime" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调取结束时间" align="center" prop="endTime" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请理由" align="center" prop="reason" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.status == 0">待审批</el-tag>
            <el-tag type="success" v-if="scope.row.status == 1">已批准</el-tag>
            <el-tag type="danger" v-if="scope.row.status == 2">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="陪同老师" align="center" prop="approverName" width="120" />
        <el-table-column label="审批时间" align="center" prop="approveTime" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleApprove(scope.row)"
              v-hasPermi="['monitor:request:edit']"
              v-if="scope.row.status == 0 && isAdmin"
            >批准</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="handleReject(scope.row)"
              v-hasPermi="['monitor:request:edit']"
              v-if="scope.row.status == 0 && isAdmin"
            >拒绝</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    <!-- 添加或修改监控调取申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" status-icon>
        <el-form-item label="申请人" prop="userId">
          <el-select
            v-model="form.userId"
            placeholder="请选择申请人"
            filterable
            :disabled="title.includes('审批')"
          >
            <el-option v-for="user in userList" :key="user.userId" :label="user.userName" :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="陪同老师" prop="approverId">
          <el-select
            v-model="form.approverId"
            placeholder="请选择陪同老师"
            filterable
            :disabled="title.includes('审批')"
          >
            <el-option v-for="user in userList" :key="user.userId" :label="user.userName" :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请地点" prop="locationId">
          <el-select
            v-model="form.locationId"
            placeholder="请选择申请地点"
            filterable
            :disabled="title.includes('审批')"
          >
            <el-option v-for="location in locationList" :key="location.locationId" :label="location.locationName" :value="location.locationId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调取时间段" prop="timeRange">
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :disabled="title.includes('审批')"
            @change="handleDateRangeChange"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input 
            v-model="form.reason" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入申请理由" 
            :disabled="title.includes('审批')"
          />
        </el-form-item>
        <el-form-item label="陪同老师意见" prop="approveComment" v-if="title.includes('审批')">
          <el-input v-model="form.approveComment" type="textarea" :rows="4" placeholder="请输入陪同老师意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" class="dialog-button" icon="el-icon-check">确 定</el-button>
        <el-button @click="cancel" class="dialog-button cancel-button" icon="el-icon-close">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 查看监控调取申请详情对话框 -->
    <el-dialog title="申请详情" :visible.sync="viewOpen" width="600px" append-to-body class="custom-dialog view-dialog">
      <el-descriptions :column="2" border>
        <template slot="title">
          <i class="el-icon-document"></i> 基本信息
        </template>
        <el-descriptions-item label="申请编号">{{ viewForm.requestId }}</el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag type="info" v-if="viewForm.status == 0" effect="plain">待审批</el-tag>
          <el-tag type="success" v-if="viewForm.status == 1" effect="plain">已批准</el-tag>
          <el-tag type="danger" v-if="viewForm.status == 2" effect="plain">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请人">{{ viewForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="申请地点">{{ viewForm.locationName }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(viewForm.startTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(viewForm.endTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="申请理由" :span="2">{{ viewForm.reason }}</el-descriptions-item>
      </el-descriptions>
      
      <el-descriptions :column="2" border v-if="viewForm.approverName || viewForm.approveTime || viewForm.approveComment" class="mt20">
        <template slot="title">
          <i class="el-icon-s-check"></i> 审批信息
        </template>
        <el-descriptions-item label="陪同老师" v-if="viewForm.approverName">{{ viewForm.approverName }}</el-descriptions-item>
        <el-descriptions-item label="审批时间" v-if="viewForm.approveTime">{{ parseTime(viewForm.approveTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="陪同老师意见" :span="2" v-if="viewForm.approveComment">{{ viewForm.approveComment }}</el-descriptions-item>
      </el-descriptions>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRequest, getRequest, delRequest, addRequest, updateRequest } from "@/api/newMonitor/request";
import { listUser } from "@/api/system/user";
import { listLocation } from "@/api/newMonitor/location";

export default {
  name: "Request",
  computed: {
    isAdmin() {
      try {
        return this.$store && this.$store.state && this.$store.state.user && 
          this.$store.state.user.roles && this.$store.state.user.roles.includes('admin');
      } catch (e) {
        console.error('获取用户角色失败', e);
        return false;
      }
    },
    currentUserId() {
      try {
        return this.$store && this.$store.getters ? this.$store.getters.userId : null;
      } catch (e) {
        console.error('获取当前用户ID失败', e);
        return null;
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控调取申请表格数据
      requestList: [],
      // 用户列表
      userList: [],
      // 地点列表
      locationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        locationId: null,
        startTime: null,
        endTime: null,
        status: null,
        approverId: null,
        approveTime: null
      },
      // 表单参数
      form: {},
      // 详情表单
      viewForm: {},
      // 时间范围
      timeRange: [],
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "申请人不能为空", trigger: "change" }
        ],
        locationId: [
          { required: true, message: "申请地点不能为空", trigger: "change" }
        ],
        timeRange: [
          { required: false, message: "调取时间段不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "调取开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "调取结束时间不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "申请理由不能为空", trigger: "blur" }
        ],
        approveComment: [
          { required: true, message: "陪同老师意见不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getLocationList();
  },
  methods: {
    /** 查询监控调取申请列表 */
    getList() {
      this.loading = true;
      listRequest(this.queryParams).then(response => {
        // 处理数据，将ID转换为名称
        const rows = response.rows || [];
        rows.forEach(row => {
          // 设置申请人名称
          const user = this.userList.find(u => u.userId == row.userId);
          row.userName = user ? user.userName : row.userId;
          
          // 设置地点名称
          const location = this.locationList.find(l => l.locationId == row.locationId);
          row.locationName = location ? location.locationName : row.locationId;
          
          // 设置陪同老师名称
          const approver = this.userList.find(u => u.userId == row.approverId);
          row.approverName = approver ? approver.userName : row.approverId;
        });
        
        this.requestList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取用户列表
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows || [];
      });
    },
    // 获取地点列表
    getLocationList() {
      listLocation().then(response => {
        this.locationList = response.rows || [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.timeRange = [];
      this.form = {
        requestId: null,
        userId: null,
        locationId: null,
        startTime: null,
        endTime: null,
        reason: null,
        status: "0",
        createTime: null,
        approverId: null,
        approveTime: null,
        approveComment: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.requestId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val) {
        this.form.startTime = val[0];
        this.form.endTime = val[1];
      } else {
        this.form.startTime = null;
        this.form.endTime = null;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 默认设置当前用户为申请人
      if (this.currentUserId) {
        this.form.userId = this.currentUserId;
      }
      this.open = true;
      this.title = "新增监控调取申请";
    },
    /** 批准按钮操作 */
    handleApprove(row) {
      this.reset();
      const requestId = row.requestId || this.ids;
      getRequest(requestId).then(response => {
        this.form = response.data;
        // 设置时间范围
        if (this.form.startTime && this.form.endTime) {
          this.timeRange = [this.form.startTime, this.form.endTime];
        }
        // 设置审批信息
        this.form.status = "1"; // 批准
        this.form.approverId = this.currentUserId;
        this.form.approveTime = new Date().toISOString().split('T')[0]; // 当前日期
        
        this.open = true;
        this.title = "审批监控调取申请";
      });
    },
    /** 拒绝按钮操作 */
    handleReject(row) {
      this.reset();
      const requestId = row.requestId || this.ids;
      getRequest(requestId).then(response => {
        this.form = response.data;
        // 设置时间范围
        if (this.form.startTime && this.form.endTime) {
          this.timeRange = [this.form.startTime, this.form.endTime];
        }
        // 设置审批信息
        this.form.status = "2"; // 拒绝
        this.form.approverId = this.currentUserId;
        this.form.approveTime = new Date().toISOString().split('T')[0]; // 当前日期
        
        this.open = true;
        this.title = "审批监控调取申请";
      });
    },
    /** 查看详情 */
    handleView(row) {
      this.viewForm = { ...row };
      this.viewOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保时间字段有值
          if (!this.form.startTime || !this.form.endTime) {
            this.$message.error("请选择调取时间段");
            return;
          }
          
          if (this.form.requestId != null) {
            updateRequest(this.form).then(response => {
              if (this.form.status === "1") {
                this.$modal.msgSuccess("申请已批准");
              } else if (this.form.status === "2") {
                this.$modal.msgSuccess("申请已拒绝");
              } else {
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
            });
          } else {
            addRequest(this.form).then(response => {
              this.$modal.msgSuccess("申请提交成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('monitor/request/export', {
        ...this.queryParams
      }, `request_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.el-tag {
  margin-right: 5px;
}

.mb8 {
  margin-bottom: 12px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px;
  margin-bottom: 15px;
}

:deep(.el-select),
:deep(.el-date-editor.el-input) {
  width: 240px;
}

:deep(.el-date-editor--date) {
  width: 240px;
}

/* 对话框样式 */
.custom-dialog {
  .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-dialog__body {
    padding: 20px 25px;
  }
  
  .el-form-item__label {
    font-weight: 500;
  }
}

/* 详情对话框样式 */
.view-dialog {
  .el-descriptions {
    padding: 15px;
    
    .el-descriptions__header {
      margin-bottom: 15px;
    }
    
    .el-descriptions__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
    
    .el-descriptions-item__label {
      color: #606266;
      font-weight: 500;
    }
    
    .el-descriptions-item__content {
      color: #303133;
    }
  }
}

.mt20 {
  margin-top: 20px;
}
</style>


